
package com.xebest.util;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code128Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

public class XeOrderBarUtil {
    private static final Logger log = LoggerFactory.getLogger(XeOrderBarUtil.class);


    /**
     * 获取订单条形码
     *
     * @author 李贝贝
     */
    public static String getBarCode(String businessId) {
        String bar = "";
        try {
            log.info("生成条形码单号{}", businessId);
            JBarcode jbcode = new JBarcode(Code128Encoder.getInstance(), WidthCodedPainter.getInstance(), EAN13TextPainter.getInstance());
            //Code128 Code Example
            jbcode.setEncoder(Code128Encoder.getInstance());
            jbcode.setPainter(WidthCodedPainter.getInstance());
            jbcode.setTextPainter(BaseLineTextPainter.getInstance());
            jbcode.setShowText(false);
            jbcode.setShowCheckDigit(false);
            BufferedImage img = jbcode.createBarcode(businessId);
            img = jbcode.createBarcode(businessId);
            bar = saveToBase64(img, "Code128.png", "png");
            return bar;
        } catch (Exception e) {
            log.error("生成条形码单号{},异常：{}", businessId, e);
        }
        return bar;
    }

    /**
     * 转换为Base64
     *
     * @author 李贝贝
     */
    public static String saveToBase64(BufferedImage paramBufferedImage, String paramString1, String paramString2) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(paramBufferedImage, "png", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());

    }
}
  
